package com.wzy.netty.core.groupchat;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.concurrent.GlobalEventExecutor;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * 描述  :
 * 创建人:    Wzy
 * 创建时间: 2020-06-11  17:06
 */
public class GroupChatServerHandler extends SimpleChannelInboundHandler<String> {

    private static ChannelGroup channelGroup = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);


    /*一旦客户端连接,第一个被执行的方法 */
    // 表示客户端的连接建立了，这是和客户端最早的接触机会
    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {

        Channel channel = ctx.channel();
        //将该客户加入聊天的信息推送至其他在线的客户端 , 这个集合会自动遍历所有注册的channel
        channelGroup.writeAndFlush("[客户端]" + channel.remoteAddress() + "加入到聊天室!"
                + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss" + "\n")));
        channelGroup.add(channel);
    }

    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();
        channelGroup.writeAndFlush("[客户端]" + channel.remoteAddress() + "离开了聊天室!"
                + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss" + "\n")));
    }

    /*表示channel处于活动状态就会触发*/
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println(ctx.channel().remoteAddress() + "上线");
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        System.out.println(ctx.channel().remoteAddress() + "下线");
    }


    /*接受客户端传送的消息*/
    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, String s) throws Exception {

        Channel channel = channelHandlerContext.channel();
        for (Channel item : channelGroup) {
            if (item != channel) {
                //不是当前 直接转发即可
                item.writeAndFlush("[用户]" + channel.remoteAddress() + "发送消息:" + s);
            } else {
                //  item.writeAndFlush("[自己]发送了消息:" + s);
            }
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
    }
}
